package com.lian.hope.interceptors;

import com.lian.hope.annotations.RequiredPermission;
import com.lian.hope.enums.PermissionType;
import com.lian.hope.model.po.Permission;
import com.lian.hope.service.UsersService;
import com.lian.hope.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.List;
import java.util.Map;

@Component
@RequiredArgsConstructor
@Slf4j
public class PermissionInterceptor implements HandlerInterceptor, Ordered {

    private final UsersService usersService;

    @Override
    public int getOrder() {
        return 1;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

        if (!(handler instanceof HandlerMethod)) return true;

        HandlerMethod handlerMethod = (HandlerMethod)handler;
        /**
         * 获取注解
         */
        RequiredPermission permission = handlerMethod.getMethodAnnotation(RequiredPermission.class);
        // 如果没有注解的值证明无需权限 直接放行
        if (permission == null) {
            return true;
        }

        /**
         * 获取注解的值
         */
        PermissionType permissionValue = permission.value();

        if (permissionValue.isEmpty()) {
            return true;
        }
        /**
         * 获取token
         */
        String token = request.getHeader("Authorization");
        log.info("token:{}", token);
        Map<String, Object> claims = JwtUtil.parseToken(token);
        log.info("claims:{}", claims);
        /**
         * 获取角色id
         */
        Integer roleId = Integer.parseInt(String.valueOf(claims.get("roleId")));
        log.info("roleId:{}", roleId);

        /**
         * 用户拥有的权限列表
         */
        List<Permission> permissions = usersService.queryPermissionByRoleId(roleId);
        log.info("permissions:{}", permissions);

        /**
         * 用户是否有该权限
         */
        boolean isMatch = permissions.stream().anyMatch(
            permission1 -> permission1.getName().equals(permissionValue.getPermission()));

        log.info("isMatch:{}", isMatch);
        if (!isMatch) {
            // 如果用户没有该权限,返回错误信息
            response.setStatus(403);
            return false    ;
        }



        return true;
    }
}
